package com.ruoyi.framework.security.service;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.EmployeeUserDetailsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 员工认证提供者
 */
@Slf4j
@Component
public class EmployeeAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private EmployeeUserDetailsServiceImpl employeeUserDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        log.info("自定义的开始认证");
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        // 检查是否是手机号格式
        if (!StringUtils.isPhone(username)) {
            log.info("用户名不是手机号格式，交给下一个提供者处理");
            // 不是手机号，返回null让下一个提供者处理
            return null;
        }
        if (!password.equals("") || password == null) {
            log.info("密码不为空，交给下一个提供者处理");
            // 密码为空，返回null让下一个提供者处理
            return null;
        }

        // 加载员工信息
        LoginUser loginUser = (LoginUser) employeeUserDetailsService.loadUserByUsername(username);
        SysUser user = loginUser.getUser();


        return new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}